import Vue from 'vue'
import VueRouter from 'vue-router'
import myRouter from './modules/my'
Vue.use(VueRouter)
// 静态
export const constantRoutes = [
  {
    path: '/login',
    name: 'login',
    meta: {},
    hidden: true,
    component: () => import('@/views/login')
  },
  {
    path: '/',
    component: () => import('@/views/layout'),
    meta: { permission: 'layout' },
    children: [
      {
        path: '/',
        name: 'home',
        meta: {
          title: '主页',
          permission: 'index'
        },
        component: () => import('@/views/home')
      },
      {
        path: '/content-con',
        name: 'content-con',
        meta: {
          title: '内容',
          permission: 'content-con'
        },
        component: () => import('@/views/content/content')
      },
      {
        path: '/cate',
        name: 'cate',
        meta: {
          title: '标签',
          permission: 'cate'
        },
        component: () => import('@/views/content/cate')
      },
      {
        path: '/article',
        name: 'article',
        meta: {
          title: '文章',
          permission: 'article'
        },
        component: () => import('@/views/content/article')
      }
    ]
  },
  {
    path: '/404',
    hidden: true,
    meta: {},
    component: () => import('@/views/404')
  }
]
// 动态
export const asyncRoutes = [
  myRouter
]

const routes = [
  // ...constantRoutes, ...asyncRoutes
  ...constantRoutes
]
const createRouter = () =>
  new VueRouter({
    // 让路由跳转后，回到头部
    scrollBehavior: () => ({ y: 0 }),
    routes
  })

const router = createRouter()
const whiteList = ['/login', '/404']

router.beforeEach((to, from, next) => {
  const Permissions = [
    'layout',
    'cate',
    'article',
    'my',
    'user',
    'history',
    'collect',
    'index'
  ]
  console.log(to, 'to')
  const { path: toPath, meta } = to
  if (whiteList.includes(toPath)) {
    next()
  } else {
    const { permission } = meta
    if (permission && Permissions.includes(permission)) {
      next()
    } else {
      next('/404')
    }
  }
})

export const resetRouter = () => {
  const newRouter = createRouter()
  router.matcher = newRouter.matcher
}
export default router
